package city.spring.modules.material.service.impl;

import city.spring.modules.material.dto.materialCategoryDTO;
import city.spring.modules.material.entity.MaterialCategoryEntity;
import city.spring.modules.material.entity.MaterialSettingEntity;
import city.spring.modules.material.repository.MaterialCategoryRepository;
import city.spring.modules.material.service.MaterialCategoryService;
import city.spring.modules.material.service.MaterialSettingService;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Service：物资类别表
 *
 * @author 谢金婷
 * @date 2020-12-10 14:18:58
 */
@CacheConfig(cacheNames = {MaterialCategoryServiceImpl.CACHE_NAME})
@Transactional(rollbackFor = Exception.class)
@Service
public class MaterialCategoryServiceImpl extends ServiceImpl<MaterialCategoryRepository, MaterialCategoryEntity> implements MaterialCategoryService {

    private final MaterialSettingService materialSettingService;

    public MaterialCategoryServiceImpl(MaterialSettingService materialSettingService) {
        this.materialSettingService = materialSettingService;
    }

    @Async
    @Override
    public void saveMaterialCategory(materialCategoryDTO entity) {
        if (!save(entity)) {
            throw new RuntimeException("保存信息失败");
        }
        Integer materials = entity.getMaterials();
//        Integer beds = entity.getBeds();
        if (materials == null || materials < 0) {
            return;
        }


        // 先保存所有货架信息
        List<MaterialSettingEntity> materialEntities = new ArrayList<>();
        for (int materialIndex = 0; materialIndex < materials; materialIndex++) {
            MaterialSettingEntity material = new MaterialSettingEntity();
            material.setId(IdWorker.getIdStr());
            material.setCategoryId(String.valueOf(entity.getId()));
            materialEntities.add(material);
        }

        materialSettingService.saveBatch(materialEntities);
    }

    @Override
    public void updateMaterialCategory(MaterialCategoryEntity entity) {
        // 使用 updateById(entity); 修改数据时，将会修改 entity 对象中所有非null数据，如果某个字段为null，将会忽略该字段的修改
        if (!updateById(entity)) {
            throw new RuntimeException("修改信息失败");
        }
    }

    @Override
    public void deleteMaterialCategory(String primaryKey) {
        removeById(primaryKey);
    }

    @Override
    public void deleteMaterialCategory(List<String> primaryKeys) {
        removeByIds(primaryKeys);
    }
}